﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Linq.Expressions;
using System.Data.Linq;
using System.IO;

public partial class Manage_ListTrains : System.Web.UI.Page
{
    protected PagedDataSource pds = new PagedDataSource();
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            BindData();
        }
    }
    private void BindData()
    {
        CmsDataContext db = new CmsDataContext();
        var q = from aT in db.Train
                where aT.District==Toolkit.CurrentUserDistrict && aT.Belong==Toolkit.CurrentUserBelong
                select aT;

        #region 检索条件
        string search = SearchConditionHidden.Value.Trim();
        if (search != "")
        {
            Expression<Func<Train, bool>> lmbda = PredicateBuilder<Train>.CreatePredicate(
                new string[] { 
                    "Name", "Address", "Course", "Subject", "Kind"}, search, "aT");
            q = q.Where(lmbda);
        } 
        #endregion

        var p = q.OrderByDescending(aT => aT.Registed).Select(aT => new
                {
                    ID = aT.ID,
                    Belong = aT.Belong,
                    Name = aT.Name,
                    Started = aT.Started,
                    Address = aT.Address,
                    Course = aT.Course,
                    Amount = aT.Amount,
                    Teacher = aT.Teacher.Name,
                    Registers = (from aJT in db.JoinTrain where aJT.TrainID == aT.ID select aJT).Count(),
                    Amended = aT.Amended,
                    CanCheck = (aT.ArticleID == null)
                });


        pds = new PagedDataSource();
        pds.AllowPaging = true;
        pds.PageSize = Toolkit.PageSize;
        pds.DataSource = p.ToList();


        #region 获取当前要显示的页
        int pageIndex = 0;
        pageIndex = Convert.ToInt32(CurrentPage.Value) - 1;
        if (pageIndex >= pds.PageCount)
        {
            pageIndex = pds.PageCount - 1;
        }
        if (pageIndex <= 0)
        {
            pageIndex = 0;
        }
        #endregion

        pds.CurrentPageIndex = pageIndex;

        TrainsView.DataSource = pds;
        TrainsView.DataBind();

        CurrentPage.Value = Convert.ToString(pageIndex + 1);
        SearchCondition.Text = SearchConditionHidden.Value.Trim();
    }
    protected void ChangePage(object sender, CommandEventArgs e)
    {
        string kind = Convert.ToString(e.CommandArgument);
        int p = Convert.ToInt32(CurrentPage.Value);

        if (kind == "F")
        {
            CurrentPage.Value = "1";
        }
        else if (kind == "P")
        {
            p--;
            CurrentPage.Value = Convert.ToString(p);
        }
        else if (kind == "N")
        {
            p++;
            CurrentPage.Value = Convert.ToString(p);
        }
        else if (kind == "L")
        {
            CurrentPage.Value = Convert.ToString(Int32.MaxValue);
        }
        else if (kind == "G")
        {
            TextBox gtp;
            foreach (Control c in TrainsView.Controls)
            {
                gtp = c.FindControl("GotoPage") as TextBox;
                if (gtp != null)
                {
                    try
                    {
                        CurrentPage.Value = Convert.ToString(Convert.ToInt32(gtp.Text.Trim()));
                    }
                    catch
                    {
                        //CurrentPage.Value = "1";
                    }

                    break;
                }
            }
        }

        BindData();
    }
    protected void Search_Click(object sender, EventArgs e)
    {
        SearchConditionHidden.Value = SearchCondition.Text.Trim();
        BindData();
    }
    protected void DeleteTrain_Click(object sender, EventArgs e)
    {
        CmsDataContext db = new CmsDataContext();
        string[] ids = Request.Params["chkID"].Split(',');

        try
        {
            string file;
            var q1 = from aT in db.Train
                     where ids.Contains(aT.ID)
                     select aT;

            foreach (Train train in q1)
            {
                //删除对应文章
                foreach (Article article in q1.Select(aT => aT.Article))
                {
                    //删除文章附件
                    foreach (Annex annex in article.Annex)
                    {
                        file = Toolkit.MappingPath(string.Format("{0}/{1}", Toolkit.PathOfUpload, annex.Url));
                        if (File.Exists(file))
                        {
                            File.Delete(file);
                        }

                        db.Annex.DeleteOnSubmit(annex);
                    }

                    //删除静态文章
                    file = Toolkit.MappingPath(string.Format("{0}/{1}", Toolkit.PathOfArticle, article.Url));
                    if (File.Exists(file))
                    {
                        File.Delete(file);
                    }

                    //删除文章
                    db.Article.DeleteOnSubmit(article);
                }

                //删除用户的注册
                db.JoinTrain.DeleteAllOnSubmit(train.JoinTrain);

                //删除项目
                db.Train.DeleteOnSubmit(train);
            }

            db.SubmitChanges();

            MessageBox.Message = "培训项目已被删除。";
            MessageBox.Location = "./ListTrains.aspx";
        }
        catch (Exception ee)
        {
            MessageBox.Message = ee.Message;
        }
    }
    protected void UploadMaterial(object sender, CommandEventArgs e)
    {
        CmsDataContext db = new CmsDataContext();
        string tid = Convert.ToString(e.CommandArgument);

        Train t = (from aT in db.Train
                   where aT.ID == tid
                   select aT).First();

        if (t.ArticleID == null)
        {
            Response.Redirect("./UploadMaterials.aspx?tid=" + tid);
        }
        else
        {
            Response.Redirect("./UploadMaterials.aspx?aid=" + t.ArticleID);
        }
    }
    protected void UploadReview(object sender, CommandEventArgs e)
    {
        CmsDataContext db = new CmsDataContext();
        string tid = Convert.ToString(e.CommandArgument);

        Train t = (from aT in db.Train
                   where aT.ID == tid
                   select aT).First();

        if (t.ReviewArticleID == null)
        {
            Response.Redirect("./EditTrainReview.aspx?tid=" + tid);
        }
        else
        {
            Response.Redirect("./EditTrainReview.aspx?aid=" + t.ReviewArticleID);
        }
    }
}